<?php

App::uses('AppController', 'Controller');

class LeavesController extends AppController {
    
    public $uses = array('Leave', 'LeaveType');
    
    public function index() {
        $conditions = array();
        if ($this->getUser('role') == 'user') {
        	$conditions = array(
        		'Leave.user_id' => $this->getUser('id')
        	);
        }
		
		$this->set('leaves', $this->Leave->find('all', array(
			'conditions' => $conditions
		)));
    }
    
    private function _setCommonData() {
        $leaveTypes = $this->LeaveType->find('list');
        $user       = $this->getUser();
        
        $this->set(compact('leaveTypes', 'user'));
        
    }
	
	public function request() {
		$this->_setCommonData();
	}
	
	public function save() {
	    if ($this->request->is('post')) {
	        $data = $this->data;
	        
	        $this->Leave->create($data);
	        
	        if (! $this->Leave->validates()) {
	            $this->_setCommonData();
	            $this->set('data', $data);
	            $this->set('errors', $this->Leave->errors);
	            $this->setFlash('Invalid data');
	            return $this->render('request');
	        }
	        
	        if (! $this->Leave->save($this->Leave->data)) {
	            $this->_setCommonData();
	            $this->set('data', $data);
	            $this->setFlash('Error saving data.');
	            return $this->render('request');
	        }
	        
	        $this->setFlash('Leave requested.', 'ok');
	    }
	    
	    return $this->redirect('index');
	}
	
	public function approve($leaveId) {
	    if ($this->Leave->save(array(
	    	'Leave' => array('id' => $leaveId, 'approved'=> 1)
	    ))) {
	        $this->setFlash('Leave approved.', 'ok');
	    } else {
	        $this->setFlash('Error approving leave.');
	    }
	    
	    $this->redirect('index');
	}
	
	public function disapprove($leaveId) {
	    if ($this->Leave->save(array(
            'Leave' => array('id' => $leaveId, 'approved'=> 0)
	    ))) {
	        $this->setFlash('Leave disapproved.', 'ok');
	    } else {
	        $this->setFlash('Error disapproving leave.');
	    }
	     
	    $this->redirect('index');
	}
    
}